﻿// JavaScript WebPart bridge
// Allows WebParts to register themselves, their clientID and providerID
// Calls are multicast from a client to all clients with matching providerIDs
// Geoff Webber-Cross
// 17/11/2010

// Client register for storing clientIDs keyed against client details object
var clientRegister = new Array();

// Register client details
function registerClient(clientID, details) {

    var index = GetRowIndex(clientID);
    if (index == -1) {
        // Add id
        clientRegister.push(jQuery.parseJSON(details));
    }
}

// Write to all webparts with matching sourceID
// This is called from the UserControlBase.JSBridgeSend method, but can be called from
// a normal page
function JSBridgeSend(clientID, args) {

    // Find matching webparts
    for (var i = 0; i < clientRegister.length; i++) {
        if (clientRegister[i].JSClientSourceID == clientID) {

            // Find SilverLight Element
            var slElement = document.getElementById(clientRegister[i].JSUniqueClientID);

            // Find Silverlight scriptable object
            var slControl = slElement.content.JSBridgeControl;

            // Write to control
            slControl.JSBridgeReceive(args);
        }
    }
}

function GetRowIndex(clientID) {
    // Look for id
    for (var i = 0; i < clientRegister.length; i++) {
        if (clientRegister[i].JSClientID == clientID) {
            return i;
            break;
        }
    }

    return -1;
}